#include "bookmanagement.h"
#include "addbookwindow.h"
#include "editbookwindow.h"
#include <QHeaderView>

BookManagement::BookManagement(Database *db, QWidget *parent)
    : QWidget(parent)
    , db(db)
{
    setupUI();
    createConnections();
    setupTableModel();
}

BookManagement::~BookManagement()
{
}

void BookManagement::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(20);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 搜索区域
    QHBoxLayout *searchLayout = new QHBoxLayout();
    searchEdit = new QLineEdit(this);
    searchEdit->setPlaceholderText("输入图书ID或名称搜索");
    searchEdit->setStyleSheet("QLineEdit { padding: 8px; border: 1px solid #BDBDBD; border-radius: 4px; }");

    searchButton = new QPushButton("搜索", this);
    searchButton->setStyleSheet("QPushButton { background-color: #2196F3; color: white; padding: 8px 16px; "
                              "border: none; border-radius: 4px; }"
                              "QPushButton:hover { background-color: #1976D2; }"
                              "QPushButton:pressed { background-color: #0D47A1; }");

    searchLayout->addWidget(searchEdit);
    searchLayout->addWidget(searchButton);
    mainLayout->addLayout(searchLayout);

    // 图书列表
    bookTableView = new QTableView(this);
    bookTableView->setStyleSheet("QTableView { border: 1px solid #BDBDBD; border-radius: 4px; }"
                               "QTableView::item { padding: 8px; }"
                               "QHeaderView::section { background-color: #2196F3; color: white; padding: 8px; }");
    bookTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    bookTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    bookTableView->setAlternatingRowColors(true);
    mainLayout->addWidget(bookTableView);

    // 按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(10);

    addButton = new QPushButton("添加图书", this);
    editButton = new QPushButton("修改图书", this);
    deleteButton = new QPushButton("删除图书", this);
    borrowButton = new QPushButton("借阅图书", this);
    returnButton = new QPushButton("归还图书", this);

    QString buttonStyle = "QPushButton { padding: 8px 16px; border: none; border-radius: 4px; }"
                         "QPushButton:hover { opacity: 0.8; }"
                         "QPushButton:pressed { opacity: 0.6; }";

    addButton->setStyleSheet(buttonStyle + "background-color: #4CAF50; color: white;");
    editButton->setStyleSheet(buttonStyle + "background-color: #FFC107; color: black;");
    deleteButton->setStyleSheet(buttonStyle + "background-color: #F44336; color: white;");
    borrowButton->setStyleSheet(buttonStyle + "background-color: #2196F3; color: white;");
    returnButton->setStyleSheet(buttonStyle + "background-color: #9C27B0; color: white;");

    buttonLayout->addWidget(addButton);
    buttonLayout->addWidget(editButton);
    buttonLayout->addWidget(deleteButton);
    buttonLayout->addWidget(borrowButton);
    buttonLayout->addWidget(returnButton);
    mainLayout->addLayout(buttonLayout);
}

void BookManagement::createConnections()
{
    connect(searchButton, &QPushButton::clicked, this, &BookManagement::onSearchClicked);
    connect(addButton, &QPushButton::clicked, this, &BookManagement::onAddBookClicked);
    connect(editButton, &QPushButton::clicked, this, &BookManagement::onEditBookClicked);
    connect(deleteButton, &QPushButton::clicked, this, &BookManagement::onDeleteBookClicked);
    connect(borrowButton, &QPushButton::clicked, this, &BookManagement::onBorrowBookClicked);
    connect(returnButton, &QPushButton::clicked, this, &BookManagement::onReturnBookClicked);
}

void BookManagement::setupTableModel()
{
    bookModel = new QSqlTableModel(this);
    bookModel->setTable("books");
    bookModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置表头
    bookModel->setHeaderData(0, Qt::Horizontal, "图书ID");
    bookModel->setHeaderData(1, Qt::Horizontal, "书名");
    bookModel->setHeaderData(2, Qt::Horizontal, "作者");
    bookModel->setHeaderData(3, Qt::Horizontal, "出版社");
    bookModel->setHeaderData(4, Qt::Horizontal, "状态");
    bookModel->setHeaderData(5, Qt::Horizontal, "入库时间");

    bookTableView->setModel(bookModel);
    bookTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    bookTableView->verticalHeader()->setVisible(false);

    refreshBookList();
}

void BookManagement::refreshBookList()
{
    bookModel->select();
}

void BookManagement::onSearchClicked()
{
    QString keyword = searchEdit->text().trimmed();
    if (keyword.isEmpty()) {
        refreshBookList();
        return;
    }

    bookModel->setFilter(QString("id LIKE '%%1%' OR title LIKE '%%1%' OR author LIKE '%%1%' OR publisher LIKE '%%1%'")
                        .arg(keyword));
    bookModel->select();
}

void BookManagement::onAddBookClicked()
{
    AddBookWindow *addWindow = new AddBookWindow(db, this);
    if (addWindow->exec() == QDialog::Accepted) {
        refreshBookList();
    }
}

void BookManagement::onEditBookClicked()
{
    QModelIndex currentIndex = bookTableView->currentIndex();
    if (!currentIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要修改的图书！");
        return;
    }

    QString bookId = bookModel->data(bookModel->index(currentIndex.row(), 0)).toString();
    EditBookWindow *editWindow = new EditBookWindow(bookId, db, this);
    if (editWindow->exec() == QDialog::Accepted) {
        refreshBookList();
    }
}

void BookManagement::onDeleteBookClicked()
{
    QModelIndex currentIndex = bookTableView->currentIndex();
    if (!currentIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的图书！");
        return;
    }

    QString bookId = bookModel->data(bookModel->index(currentIndex.row(), 0)).toString();
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除",
        "确定要删除这本图书吗？", QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        if (db->deleteBook(bookId)) {
            QMessageBox::information(this, "成功", "图书删除成功！");
            refreshBookList();
        } else {
            QMessageBox::warning(this, "错误", "图书删除失败！");
        }
    }
}

void BookManagement::onBorrowBookClicked()
{
    QModelIndex currentIndex = bookTableView->currentIndex();
    if (!currentIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要借阅的图书！");
        return;
    }

    QString bookId = bookModel->data(bookModel->index(currentIndex.row(), 0)).toString();
    bool available = bookModel->data(bookModel->index(currentIndex.row(), 4)).toBool();

    if (!available) {
        QMessageBox::warning(this, "警告", "该图书已被借出！");
        return;
    }

    BorrowWindow *borrowWindow = new BorrowWindow(bookId, db, this);
    if (borrowWindow->exec() == QDialog::Accepted) {
        refreshBookList();
    }
}

void BookManagement::onReturnBookClicked()
{
    QModelIndex currentIndex = bookTableView->currentIndex();
    if (!currentIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要归还的图书！");
        return;
    }

    QString bookId = bookModel->data(bookModel->index(currentIndex.row(), 0)).toString();
    bool available = bookModel->data(bookModel->index(currentIndex.row(), 4)).toBool();

    if (available) {
        QMessageBox::warning(this, "警告", "该图书未被借出！");
        return;
    }

    ReturnWindow *returnWindow = new ReturnWindow(bookId, db, this);
    if (returnWindow->exec() == QDialog::Accepted) {
        refreshBookList();
    }
} 